<?php

namespace qywxmsgsdk\Provider;

use qywxmsgsdk\Contract\ProviderInterface;
use qywxmsgsdk\Exception\FinanceSDKException;
use qywxmsgsdk\Exception\InvalidArgumentException;

/**
 * PHP会话存档扩展
 * @package qywxmsgsdk\Provider
 */
class PHPExtProvider extends AbstractProvider
{
    /**
     * @var array
     */
    protected $config = [];

    /**
     * @var ChatSdk
     */
    private $financeSdk;

    /**
     * {@inheritdoc}
     */
    public function setConfig(array $config): ProviderInterface
    {
        $this->config = array_merge($this->config, $config);
        $this->setFinanceSDK();
        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getConfig(): array
    {
        return $this->config;
    }

    /**
     * {@inheritdoc}
     */
    public function getChatData(int $seq, int $limit): string
    {
        return $this->financeSdk->getChatData($seq, $limit);
    }

    /**
     * {@inheritdoc}
     */
    public function decryptData(string $randomKey, string $encryptStr): string
    {
        return $this->financeSdk->decryptData($randomKey, $encryptStr);
    }

    /**
     * {@inheritdoc}
     * @throws FinanceSDKException
     */
    public function getMediaData(string $sdkFileId, string $ext): \SplFileInfo
    {
        $tmp_dir = $this->config['tmp_dir'] ?? sys_get_temp_dir();
        if (!is_dir($tmp_dir)) {
            mkdir($tmp_dir, 0755, true);
        }
        $path = $tmp_dir . DIRECTORY_SEPARATOR . md5(time() . random_int(100000, 999999));
        $ext && $path .= '.' . $ext;
        try {
            $this->financeSdk->downloadMedia($sdkFileId, $path);
        } catch (\Exception $e) {
            throw new FinanceSDKException('获取文件失败' . $e->getMessage(), $e->getCode());
        }
        return new \SplFileInfo($path);
    }

    /**
     * 获取php-ext-sdk.
     * @param array $config
     * @throws InvalidArgumentException|FinanceSDKException
     */
    protected function setFinanceSDK(array $config = []): void
    {
        $this->config = array_merge($this->config, $config);
        if (!isset($this->config['corpid'])) {
            throw new InvalidArgumentException('缺少配置:corpid');
        }
        if (!isset($this->config['secret'])) {
            throw new InvalidArgumentException('缺少配置:secret');
        }
        $options = ['timeout' => 30];
        isset($this->config['proxy']) && $options['proxy_host'] = $this->config['proxy'];
        isset($this->config['passwd']) && $options['proxy_password'] = $this->config['passwd'];
        isset($this->config['timeout']) && $options['timeout'] = $this->config['timeout'];
        $this->financeSdk = new ChatSdk(
            $this->config['corpid'],
            $this->config['secret'],
            $options
        );
    }
}
